﻿using Microsoft.AspNetCore.Http;
using Syspetro.Core.AppDeal;
using Syspetro.Core.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.Core.HttpService
{
    public class HttpForward
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public HttpForward(IHttpContextAccessor httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;

        }
        public (bool status, T data, string msg) Get<T>(string url, string route, bool isAuthentication = true)
        {
            try
            {
                HttpClient _client = new();
                if (isAuthentication)
                    AddDefaultHeaders(_client);
                var response = _client.GetAsync(url + route).Result;
                var data = new SpActionResult<T>();
                return response.IsSuccessStatusCode ? (true, response.Content.ReadAsStringAsync().Result.ToObject<T>(), string.Empty) : (false, default, response.ReasonPhrase);
            }
            catch (Exception ex)
            {
                return (false, default, ex.Message);
            }

        }
        public (bool status, T data, string msg) Post<T>(string url, string route, Dictionary<string, object> param = null, bool isAuthentication = true)
        {
            try
            {
                HttpClient _client = new();
                if (isAuthentication)
                    AddDefaultHeaders(_client);
                var response = _client.PostAsync(url + route, new JsonContent(param)).Result;
                return response.IsSuccessStatusCode ? (true, response.Content.ReadAsStringAsync().Result.ToObject<T>(), string.Empty) : (false, default, response.ReasonPhrase);
            }
            catch (Exception ex)
            {
                return (false, default, ex.Message);
            }
        }

        private void AddDefaultHeaders(HttpClient httpClient)
        {
            var headers = _httpContextAccessor.HttpContext.Request.Headers;
            if (headers != null)
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", headers["Authorization"].ToString());
                httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
            }
        }
    }
}
